<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;
use app\admin\model\Goods as GoodsModel;
use app\admin\model\Category as CategoryModel;

class Goods extends Controller
{
    //初始化
    protected $db;

    public function _initialize()
    {//构造方法
        parent::_initialize();
        $this->db = new GoodsModel();
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $goods = Db::table('details')->order('shop_sort desc')->where('shop_del', 1)->paginate(10);

        $this->assign('goods', $goods);
        return view();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public   function post()
    {
        $de_id = input('param.de_id');
        $model = $de_id ? GoodsModel::find($de_id) : new GoodsModel();
        if (request()->isPost()) {

            $post = input('post.');
//            halt($post);
            $post['pics'] = implode('@', $post['pics']);
//            halt($post);
            $res = $model->validate(true)->allowField(true)->save($post);
            if ($res) {
                $this->success('商品添加成功', 'index');
            } else {
                $this->error($model->getError());
            }
        }
        if (!$de_id) {
            $model = ['de_name' => '', 'shop_sort' => 0, 'now_price' => 0, 'stock' => 0, 'sell_out' => 0, 'shop_color' => '', 'shop_size' => '', 'shop_thumb' => '', 'pics' => '', 'describe' => ''];
        }
        $Category=(new CategoryModel)->getAllCate();
        return view('', compact('model','Category'));
    }

    /**
     * 商品下架的方法
     */
    public function down()
    {
        $de_id = input('get.de_id');
        $res= Db::table('details') ->where('de_id',$de_id)->setField('shop_del', 0);
        if ($res) {
            $this->success('完成下架', 'index');
        } else {
            $this->error('商品下架失败');
        }
    }
    /**
     * 异步删除图片
     */
    public function delImg(){
        if(request()->isAjax()){
            $path = input('post.path');
            //http://shop.ishilf.com/uploads/20170713/108fa238ce1381dbbfd364c1cf3fe402.jpg
            //halt(is_file('uploads/20170713/108fa238ce1381dbbfd364c1cf3fe402.jpg'));
            //halt($path);
            //$a = 'uploads/20170713/108fa238ce1381dbbfd364c1cf3fe402.jpg';
            $path = strrchr($path,'uploads');
            if(is_file($path)){
                unlink($path);
                echo 1;die;
            }
            echo 0;die;
        }
    }


}
